import 'dart:convert';
import 'dart:math';

import 'package:winkai/entity/role_info.dart';
import 'package:winkai/entity/msg_constant.dart';
import 'package:drift/drift.dart';
import 'package:winkai/ext/ext.dart';
import 'package:winkai/helper/user_helper.dart';

import 'dao/msg_dao.dart';
import 'dao/ses_dao.dart';
import 'database.dart';

extension StringExt on String {
  Value<String> get toDrifiteValue {
    return Value(this);
  }
}

extension StringNullSafeExt on String? {
  Value<String?> get toDrifitNullSafeValue {
    return this?.isNotEmpty == true ? Value(this) : const Value.absent();
  }
}

extension IntExt on int {
  Value<int> get toDrifitValue {
    return Value(this);
  }
}

extension IntNullSafeExt on int? {
  Value<int?> get toDrifitNullSafeValue {
    return this != null ? Value(this) : const Value.absent();
  }
}

extension DateTimeExt on DateTime {
  Value<DateTime> get toDrifitValue {
    return Value(this);
  }
}

extension DateTimeNullSafeExt on DateTime? {
  Value<DateTime> get toDrifitNullSafeValue {
    return this != null ? Value(this!) : const Value.absent();
  }
}

extension BoolExt on bool {
  Value<bool> get toDrifitValue {
    return Value(this);
  }
}

extension BoolNullSafeExt on bool? {
  Value<bool?> get toDrifitNullSafeValue {
    return this != null ? Value(this) : const Value.absent();
  }
}

enum GenIdScope {
  simple('10'),
  appointment('11');

  const GenIdScope(this.code);

  final String code;
}

/// 生成会话id
String genSessionId({
  required RoleInfo aiRoleInfo,
  SesType sessionType = SesType.single,
}) {
  var userId = UserHelper().userId;
  var type = sessionType.name;
  var id = aiRoleInfo.id ?? '';
  var name = aiRoleInfo.name ?? '';
  return '$userId-$type->$id:$name';
}

/// 生成消息id
int genMsgId({
  GenIdScope scope = GenIdScope.simple,
  int? value,
}) {
  if (value != null) {
    return int.parse('${scope.code}$value');
  }
  var start = DateTime(2023, 4).millisecondsSinceEpoch;
  var time = DateTime.now().millisecondsSinceEpoch - start;
  return int.parse('${scope.code}$time${Random().nextInt(999)}');
}

/// 生成消息发送id
int genSendId({
  GenIdScope scope = GenIdScope.simple,
  int? value,
}) {
  if (value != null) {
    return int.parse('${scope.code}$value');
  }
  var start = DateTime(2023, 4).millisecondsSinceEpoch;
  var time = DateTime.now().millisecondsSinceEpoch - start;
  return int.parse('${scope.code}$time${Random().nextInt(999)}');
}

extension $UserTbTableExtension on $UserTbTable {
  Expression<bool> get accountExpr {
    return accountId.equals(UserHelper().userId);
  }
}

extension $MsgTbTableExtension on $MsgTbTable {
  Expression<bool> get accountExpr {
    return accountId.equals(UserHelper().userId);
  }
}

extension $SesTbTableExtension on $SesTbTable {
  Expression<bool> get accountExpr {
    return accountId.equals(UserHelper().userId);
  }
}

extension SesTbDataExtension on SesTbData {
  /// 用户或群组id
  String get identity {
    return userId ?? "0";
  }

  /// 是否单聊
  bool get isSingle {
    return userId != null;
  }
}

extension MsgTbDataExtension on MsgTbData {
  Map<String, Object> get contentJson {
    try {
      if (RegExp(r'{*}$').hasMatch(content)) {
        final res = jsonDecode(content) as Map<String, dynamic>;
        final result = <String, Object>{};
        res.forEach((key, value) {
          if (value != null) {
            result[key] = value;
          }
        });
        return result;
      }
    } catch (e) {}
    return {};
  }

  /// 是否自己
  bool get isSelf {
    return UserHelper().userId == userId;
  }
}

extension UserTbDataExtension on UserTbData {
  String get name {
    if (nickname.isEmpty) {
      return id;
    }
    return nickname;
  }
}

extension MessageInfoExtension on MsgInfo {
  String get name {
    if (user?.nickname.isNotEmpty == true) {
      return (user?.nickname)!;
    }
    return '';
  }

  String get avatar {
    return user?.avatar ?? '';
  }
}

extension SessionInfoExtension on SesInfo {
  String get name {
    return user?.nickname.replaceLineBreak ?? '';
  }

  String get avatar {
    return user?.avatar ?? '';
  }

  /// 消息
  MsgInfo? get messageInfo {
    if (message == null) {
      return null;
    }
    return MsgInfo(
      msg: message!,
      session: session,
      user: msgUser,
    );
  }
}

/// 表达式工厂
Expression<bool> exprFactory(Iterator<Expression<bool>> items) {
  Expression<bool> prev = const Constant(true);
  while (items.moveNext()) {
    prev = prev & items.current;
  }
  return prev;
}
